import './public-path'
import '@/asset/css/style'
import { App as VApp, createApp } from 'vue'
import { PlatformFrameProps } from 'qiankun-frame'
import { appName } from '@/config'
import { QiankunApp } from '@lhy-assist/qiankun'
import App from './App.vue'
import plugin from './plugin'
import { qiankunApp } from './qiankun/qiankun-app'
import { Router } from './router'

export class VueApp {
  /**
   * 实例
   *
   * @protected
   * @static
   * @type {(VApp<Element> | null)}
   * @memberOf VueApp
   */
  protected static app: VApp<Element> | null = null

  /**
   * 渲染实例
   *
   * @static
   * @param {HTMLElement} [container]
   * @param {string} [activeRule]
   *
   * @memberOf VueApp
   */
  public static render(container?: HTMLElement, activeRule?: string) {
    const app = (this.app = createApp(App))
    app.use(plugin)
    app.use(Router.create(activeRule))

    app.mount(container ? (container.querySelector('#app') as HTMLElement) : '#app')
  }

  /**
   * 销毁
   *
   * @static
   *
   * @memberOf VueApp
   */
  public static destroy() {
    this.app?.unmount()
    this.app = null
  }
}

// 非qiankun子应用时独立启动app
if (!QiankunApp.active) {
  VueApp.render()
}

// ************* 暴露钩子函数给qiankun ************* //
export async function bootstrap() {
  console.log(`${appName} bootstrap`)
}
export async function mount(props: PlatformFrameProps) {
  console.log(`${appName} mount`)
  qiankunApp.initFrame(props)
  VueApp.render(props.container, props.activeRule)
}
export async function unmount() {
  console.log(`${appName} unmount`)
  VueApp.destroy()
  Router.destroy()
}
